<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { isLoggedIn, getUserInfo } from '../utils/auth.js'
import { useUserWebSocketStore } from '../stores/websocket'
import { showToast } from 'vant'

const router = useRouter()
const wsStore = useUserWebSocketStore()

// 用户信息
const userInfo = ref(null)
const isUserLoggedIn = ref(false)

// 消息列表
const messages = ref([])

// 输入框内容
const inputText = ref('')
const inputHeight = ref(48)

// 快捷回复选项
const quickReplies = ref([
  { text: '订单咨询', icon: '📋' },
  { text: '退改签', icon: '🔄' },
  { text: '发票问题', icon: '🧾' },
  { text: '投诉建议', icon: '💬' }
])

// 是否显示快捷回复
const showQuickReplies = computed(() => {
  return messages.value.length <= 1 && inputText.value === ''
})

// 客服信息
const serviceInfo = ref({
  name: '客服小程',
  avatar: '👨‍💼',
  status: 'online', // online, offline, away
  statusText: '在线'
})

// WebSocket 连接状态
const isConnected = computed(() => wsStore.isConnected)

// 输入框引用
const inputRef = ref(null)
const messagesContainer = ref(null)

// 消息处理器
const handleMessage = (messageData) => {
  console.log('收到消息:', messageData)
  
  // 忽略状态消息
  if (messageData.status) {
    return
  }
  
  // 忽略用户信息通知（用户上线时发送给医生的）
  if (messageData.userid) {
    return
  }
  
  // 处理客服发给当前用户的消息
  // 根据后端逻辑：医生发送给用户时，from 是 'service1001'，to 是用户ID
  const serviceId = '1001'
  const serviceFrom = `service${serviceId}`
  
  // 判断是否是从医生发来的消息
  if (messageData.from === serviceFrom && messageData.to === wsStore.userId) {
    // 医生发来的消息
    const serviceMessage = {
      id: Date.now(),
      type: 'service',
      content: messageData.message || messageData.content || '',
      timestamp: messageData.timestamp ? new Date(messageData.timestamp).getTime() : new Date().getTime(),
      avatar: '👨‍💼'
    }
    messages.value.push(serviceMessage)
    
    // 更新客服状态为在线
    serviceInfo.value.status = 'online'
    serviceInfo.value.statusText = '在线'
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } else {
    // 可能是自己发送的消息被回显（后端转发回来的），可以忽略或处理
    console.log('收到其他消息:', messageData)
  }
}

onMounted(() => {
  checkLoginStatus()
  initWebSocket()
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
})

onUnmounted(() => {
  // 移除消息处理器
  wsStore.unregisterMessageHandler('consultation')
  // 离开咨询页面时断开连接
  wsStore.disconnectConsultation()
})

const checkLoginStatus = () => {
  isUserLoggedIn.value = isLoggedIn()
  if (isUserLoggedIn.value) {
    userInfo.value = getUserInfo()
  } else {
    // 未登录时提示用户，但允许查看页面
    showToast('请先登录以使用咨询服务')
  }
}

// 初始化 WebSocket - 只在进入咨询页面时建立连接
const initWebSocket = () => {
  if (!isUserLoggedIn.value) {
    return
  }

  // 在咨询页面建立独立的 WebSocket 连接
  // 连接 key 为: user_id + service_id (1001)，由后端自动处理
  if (!wsStore.isConnected) {
    wsStore.initConsultation()
  }
  
  // 注册消息处理器
  wsStore.registerMessageHandler('consultation', handleMessage)
  
  // 等待连接成功后再显示欢迎消息
  const checkConnection = setInterval(() => {
    if (wsStore.isConnected && messages.value.length === 0) {
      const welcomeMessage = {
        id: Date.now(),
        type: 'service',
        content: '您好！欢迎使用同程旅行在线咨询服务，我是您的专属客服。有什么可以帮助您的吗？',
        timestamp: new Date().getTime(),
        avatar: '👨‍💼'
      }
      messages.value.push(welcomeMessage)
      clearInterval(checkConnection)
    }
  }, 100)
  
  // 5秒后停止检查
  setTimeout(() => {
    clearInterval(checkConnection)
  }, 5000)
}

// 发送消息
const sendMessage = () => {
  if (!inputText.value.trim()) {
    return
  }

  // 检查登录状态
  if (!isUserLoggedIn.value) {
    showToast('请先登录')
    setTimeout(() => {
      router.push('/user/login')
    }, 1500)
    return
  }

  // 检查 WebSocket 连接状态
  if (!wsStore.isConnected) {
    showToast('未连接到服务器，请稍后再试')
    // 尝试重新连接
    initWebSocket()
    return
  }

  const messageContent = inputText.value.trim()

  // 添加用户消息（乐观更新）
  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: messageContent,
    timestamp: new Date().getTime(),
    avatar: userInfo.value?.avatar_url || '👤'
  }
  
  messages.value.push(userMessage)
  inputText.value = ''
  inputHeight.value = 48
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })

  // 通过 WebSocket 发送消息
  const success = wsStore.sendMessage(messageContent)
  
  if (!success) {
    showToast('发送失败，请重试')
    // 如果发送失败，可以考虑从消息列表中移除刚添加的消息
    // messages.value.pop()
  }
}

// 快捷回复点击
const handleQuickReply = (reply) => {
  inputText.value = reply.text
  sendMessage()
}

// 输入框高度自适应
const adjustInputHeight = () => {
  if (inputRef.value) {
    inputRef.value.style.height = '48px'
    inputRef.value.style.height = Math.min(inputRef.value.scrollHeight, 120) + 'px'
    inputHeight.value = Math.min(inputRef.value.scrollHeight, 120)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const msgDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  
  if (msgDate.getTime() === today.getTime()) {
    // 今天显示时间
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    // 其他日期显示日期和时间
    return date.toLocaleString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
}

// 格式化消息时间（用于显示在消息之间）
const shouldShowTime = (currentMsg, prevMsg) => {
  if (!prevMsg) return true
  const timeDiff = currentMsg.timestamp - prevMsg.timestamp
  return timeDiff > 300000 // 5分钟
}

// 添加表情（扩展功能）
const addEmoji = (emoji) => {
  inputText.value += emoji
}

// 清空输入框
const clearInput = () => {
  inputText.value = ''
  inputHeight.value = 48
  if (inputRef.value) {
    inputRef.value.style.height = '48px'
  }
}
</script>

<template>
  <div class="consultation-page">
    <!-- 顶部导航栏 -->
    <div class="chat-header">
      <div class="header-left" @click="router.back()">
        <span class="back-icon">←</span>
      </div>
      <div class="header-center">
        <div class="service-avatar">{{ serviceInfo.avatar }}</div>
        <div class="service-info">
          <div class="service-name">{{ serviceInfo.name }}</div>
          <div class="service-status">
            <span :class="['status-dot', isConnected ? 'online' : 'offline']"></span>
            <span class="status-text">{{ isConnected ? '在线' : '连接中...' }}</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <span class="more-icon" @click="showToast('更多功能')">⋯</span>
      </div>
    </div>

    <!-- 消息列表容器 -->
    <div ref="messagesContainer" class="messages-container">
      <!-- 消息列表 -->
      <div class="messages-list">
        <div 
          v-for="(message, index) in messages" 
          :key="message.id"
          class="message-wrapper"
        >
          <!-- 时间戳 -->
          <div v-if="shouldShowTime(message, messages[index - 1])" class="time-divider">
            {{ formatTime(message.timestamp) }}
          </div>

          <!-- 消息气泡 -->
          <div :class="['message-item', message.type]">
            <!-- 头像 -->
            <div class="message-avatar">
              {{ message.type === 'service' ? serviceInfo.avatar : (userInfo?.avatar_url ? '' : '👤') }}
              <img v-if="message.type === 'user' && userInfo?.avatar_url" :src="userInfo.avatar_url" alt="avatar" />
            </div>

            <!-- 消息内容 -->
            <div class="message-content">
              <div class="message-bubble" :class="message.type">
                <div class="message-text">{{ message.content }}</div>
              </div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 快捷回复 -->
      <div v-if="showQuickReplies" class="quick-replies">
        <div 
          v-for="reply in quickReplies" 
          :key="reply.text"
          class="quick-reply-item"
          @click="handleQuickReply(reply)"
        >
          <span class="reply-icon">{{ reply.icon }}</span>
          <span class="reply-text">{{ reply.text }}</span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-container">
        <!-- 表情按钮（可选） -->
        <button class="input-btn emoji-btn" @click="addEmoji('😊')" title="表情">
          😊
        </button>

        <!-- 输入框 -->
        <textarea
          ref="inputRef"
          v-model="inputText"
          class="message-input"
          placeholder="请输入消息..."
          rows="1"
          @input="adjustInputHeight"
          @keydown.enter.prevent="sendMessage"
        ></textarea>

        <!-- 发送按钮 -->
        <button 
          :class="['send-btn', { active: inputText.trim() }]"
          @click="sendMessage"
          :disabled="!inputText.trim()"
        >
          <span v-if="inputText.trim()" class="send-text">发送</span>
          <span v-else class="send-icon">🎤</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.consultation-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
  overflow: hidden;
}

/* 顶部导航栏 */
.chat-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left,
.header-right {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.back-icon,
.more-icon {
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.header-center {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: center;
}

.service-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.service-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.service-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.service-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #999;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
}

.status-dot.online {
  background: #52c41a;
  box-shadow: 0 0 6px rgba(82, 196, 26, 0.5);
}

.status-dot.offline {
  background: #ccc;
}

.status-dot.away {
  background: #faad14;
}

/* 消息容器 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  scroll-behavior: smooth;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 时间分隔线 */
.time-divider {
  text-align: center;
  font-size: 12px;
  color: #999;
  padding: 8px 0;
  position: relative;
}

.time-divider::before,
.time-divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30%;
  height: 1px;
  background: #e8e8e8;
}

.time-divider::before {
  left: 0;
}

.time-divider::after {
  right: 0;
}

/* 消息项 */
.message-wrapper {
  display: flex;
  flex-direction: column;
}

.message-item {
  display: flex;
  gap: 8px;
  max-width: 80%;
  animation: fadeInUp 0.3s ease-out;
}

.message-item.user {
  flex-direction: row-reverse;
  margin-left: auto;
}

.message-item.service {
  flex-direction: row;
  margin-right: auto;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
  overflow: hidden;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-item.user .message-content {
  align-items: flex-end;
}

.message-item.service .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 12px;
  word-wrap: break-word;
  word-break: break-word;
  position: relative;
  max-width: 100%;
}

.message-bubble.service {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-top-left-radius: 4px;
}

.message-bubble.user {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-top-right-radius: 4px;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  color: inherit;
}

.message-time {
  font-size: 11px;
  color: #999;
  padding: 0 4px;
}

/* 快捷回复 */
.quick-replies {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 16px;
  padding: 12px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.quick-reply-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 14px;
  background: #f5f5f5;
  border-radius: 20px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e8e8e8;
}

.quick-reply-item:active {
  background: #e8e8e8;
  transform: scale(0.95);
}

.reply-icon {
  font-size: 14px;
}

.reply-text {
  font-weight: 500;
}

/* 输入区域 */
.input-area {
  background: #fff;
  border-top: 1px solid #e8e8e8;
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  background: #f5f5f5;
  border-radius: 24px;
  padding: 8px 12px;
}

.input-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  padding: 0;
  transition: transform 0.2s;
}

.input-btn:active {
  transform: scale(0.9);
}

.message-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 14px;
  color: #333;
  resize: none;
  outline: none;
  max-height: 120px;
  min-height: 32px;
  line-height: 1.5;
  padding: 4px 0;
  font-family: inherit;
}

.message-input::placeholder {
  color: #999;
}

.send-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.2s;
  font-size: 18px;
  padding: 0;
}

.send-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: auto;
  padding: 0 12px;
  border-radius: 16px;
}

.send-btn.active .send-text {
  font-size: 14px;
  color: #fff;
  font-weight: 500;
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.send-icon {
  font-size: 18px;
}

/* 动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 4px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 2px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .message-item {
    max-width: 85%;
  }

  .service-avatar {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }

  .service-name {
    font-size: 15px;
  }
}

/* 安全区域适配 */
.input-area {
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
}
</style>

